/*
 * 路由封装
 * @author Leriy
*/
import { createRouter, createWebHistory } from 'vue-router';
import { getCookie } from '@/utils/storage.js'

const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue')
    },
    {
        path: '/',
        name: 'Home',
        component: () => import("@/layout/Index.vue"),
        redirect: '/index',
        children: [
            {
                path: '/index',
                name: 'Index',
                component: () => import("@/views/Index.vue"),
            },
            {
                path: '/users',
                name: 'Users',
                component: () => import("@/views/users/Index.vue"),
            },
            {
                path: '/menus',
                name: 'Menus',
                component: () => import("@/views/menus/Index.vue"),
            },
            {
                path: '/roles',
                name: 'Roles',
                component: () => import("@/views/roles/Index.vue"),
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const { name } = to
    const { path } = from
    const { token } = getCookie('userInfo') ? JSON.parse(getCookie('userInfo')) : ''

    // 已登录状态访问登录页，重定向到原来页面
    if (name == 'Login' && token) return next(path)

    // 登录页直接放行
    if (name == 'Login') return next()

    // 判断有无 Token ，没有重定向到 Login
    if (!token) return next({ name: 'Login' })

    // 正常访问
    next()
})

export default router